package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Autowired
    private ServeItemMapper serveItemMapper;
    @Autowired
    private RegionMapper regionMapper;



    /**
     * 分页查询Service方法
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> Page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //分页查询方法（第一种：MyBatisPlus 【不建议自定义SQL实现多表联查】  第二种pageHelper[√]）

        return PageHelperUtils.selectPage(servePageQueryReqDTO, new PageHelperUtils.QueryExecutor<ServeResDTO>() {
            @Override
            public List<ServeResDTO> query() {
                return getBaseMapper().queryServeListByRegionId(servePageQueryReqDTO.getRegionId());
            }
        });
    }

    /**
     * 新增区域服务
     * @param serveUpsertReqDTOS
     */
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOS) {
        //1.循环传入的DTO数据
        serveUpsertReqDTOS.forEach(sd->{
            //2.数据校验
            //2.1 服务项（serve_item）是否存在，是否启用
            ServeItem serveItem = serveItemMapper.selectOne(Wrappers.<ServeItem>lambdaQuery().eq(ServeItem::getId,sd.getServeItemId()));
            if (serveItem==null || serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
                throw new ForbiddenOperationException("该服务未启用或不存在！");
            }
            //2.2 当前区域是否已经添加过该服务项
            Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery()
                    .eq(Serve::getServeItemId,sd.getRegionId())
                    .eq(Serve::getRegionId,sd.getRegionId()));
            if (count>0){
                throw  new ForbiddenOperationException("该服务项不能重复添加！");
            }
            //2.3 区域是否存在
            Region region = regionMapper.selectOne(Wrappers.<Region>lambdaQuery().eq(Region::getId,sd.getRegionId()));
            if (region==null){
                throw new ForbiddenOperationException("该区域尚未开通");
            }
            //3.循环添加数据到serve表中
            Serve serve = BeanUtil.toBean(sd,Serve.class);
            serve.setCityCode(region.getCityCode());
            serve.setPrice(serveItem.getReferencePrice());
            getBaseMapper().insert(serve);
        });
    }

    /**
     * 修改区域服务价格
     * @param id
     * @param price
     */
    @Override
    public void update(Long id, BigDecimal price) {
        boolean bo = lambdaUpdate().eq(Serve::getId, id).set(Serve::getPrice, price).update();
        if (!bo){
            throw new ForbiddenOperationException("价格修改失败！");
        }
    }

    /**
     * 区域服务上架
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //1.当前区域服务（serve）必须是草稿或者下架状态
        Serve serve = getById(id);
        if (serve==null || (serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus())){
            throw new ForbiddenOperationException("当前服务启动失败！");
        }

        //2、该服务对应的服务项（serve_item）必须是启用状态
        ServeItem serveItem = serveItemMapper.selectOne(Wrappers.<ServeItem>lambdaQuery().eq(ServeItem::getId,serve.getServeItemId()));
        if (serveItem==null || serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new ForbiddenOperationException("当前服务项状态不正确！");
        }

        //3.上架操作
        boolean update = lambdaUpdate().set(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .eq(Serve::getId, id)
                .update();
        if (!update){
            throw new ForbiddenOperationException("服务上架失败！");
        }
    }

    /**
     * 删除区域服务
     * @param id
     */
    @Override
    public void delete(Long id) {
        //1.服务状态草稿才能删除
        //2.删除
        boolean remove = remove(Wrappers.<Serve>lambdaQuery().eq(Serve::getId, id).eq(Serve::getSaleStatus, FoundationStatusEnum.INIT.getStatus()));
        if (!remove){
            throw new ForbiddenOperationException("删除服务失败！请检查服务状态是否正确！");
        }
    }
    /**
     * 服务下架
     */
    @Override
    public void offSale(Long id) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus())
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus()).update();
        if (!update){
            throw new ForbiddenOperationException("下架服务失败！");
        }
    }

    /**
     * 设置服务热门
     */
    @Override
    public void onHot(Long id) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 1).update();
        if (!update){
            throw new ForbiddenOperationException("设置热门服务失败！");
        }
    }

    /**
     * 设置服务非热门
     */
    @Override
    public void offHot(Long id) {
        boolean update = lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, 0).update();
        if (!update){
            throw new ForbiddenOperationException("设置热门非服务失败！");
        }

    }

    @Override
    public Long serveOnSaleCount(Long id) {
        Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getRegionId,id)
                .eq(Serve::getSaleStatus,FoundationStatusEnum.ENABLE.getStatus())
        );
        return count;
    }

    @Override
    public Long serveOnSaleNumber(Long id) {
        Long count = getBaseMapper().selectCount(Wrappers.<Serve>lambdaQuery().eq(Serve::getServeItemId, id)
                .eq(Serve::getSaleStatus, FoundationStatusEnum.ENABLE.getStatus()));
        return count;
    }
}
